package com.slowly.intercepto;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.slowly.kit.HttpKit;

/**
 * 登录拦截器
 * 
 * @author xuping
 * 
 */
public class LoginInterceptor implements Interceptor {
	
	public void intercept(Invocation inv) {
		Controller contr = inv.getController();
		if (inv.getActionKey().startsWith("/admin")) { // 如果为管理后台请求
			if (contr.getSessionAttr("cAdmin") == null) {
				String basePath = HttpKit.getContextPath(contr.getRequest());
				String backUrl = basePath + inv.getActionKey();
				String queryString = contr.getRequest().getQueryString();
				if (StrKit.notBlank(queryString)) {
					if (backUrl.indexOf("?") == -1) {
						backUrl = backUrl + "?" + queryString;
					} else {
						backUrl = backUrl + "&" + queryString;
					}
				}
				if (StrKit.notBlank(contr.getPara("ajax"))) {// 如果是ajax请求
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("success", false);
					map.put("code", "0001");
					map.put("redirectUrl", basePath + "/admin/login?backUrl=" + backUrl);
					map.put("msg", "亲,还请先登录一下下...");
					contr.renderJson(map);
					return;
				} else {
					contr.redirect("/admin/login?backUrl=" + backUrl);
					return;
				}
			}
		}
		inv.invoke();
	}
}
